﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace DuplicationDetection
{
    public class FileInfoEx: IComparable<FileInfoEx>
    {
        public string FullPath{get; private set;}
        private string _MD5 = null;
        public string MD5 {
            get
            {
                if (_MD5 == null)
                {
                    _MD5 = ComputeMD5();
                }
                return _MD5;
            }
        }

        public string ComputeMD5()
        {
            try
            {
                using (FileStream fs = File.OpenRead(this.FullPath))
                {
                    RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create();
                    return Convert.ToString(myRIPEMD160.ComputeHash(fs));
                }

            }
            catch (Exception)
            {

                return null;
            }
          

        }
        private long size = -1;
        private DateTime lastModified;
        private string extension = null;

        
        private FileInfoEx(string fullPath, long size)
        {
            this.FullPath = fullPath;
            this.size = size;
            this.extension = Path.GetExtension(fullPath);
        }

        public static FileInfoEx CreateFileInfo(string fullPath)
        {
            if (File.Exists(fullPath))
            {
                using (var tr = File.OpenRead(fullPath))
                {
                    return new FileInfoEx(Path.GetFullPath(fullPath), tr.Length);                   
                }
            }
            return null;
        }

        public bool Equals(FileInfoEx obj)
        {
            return this.CompareTo(obj) == 0;
        }
        public int CompareTo(FileInfoEx obj)
        {
            if (this.size != obj.size)
            {
                return (int)(this.size - obj.size);
            }

            if (this.MD5 == obj.MD5)
            {
                return 0;
            }
            else
            {
                return string.Compare(this.MD5, obj.MD5);
            }
        }
    }
}
